package org.xnsg.app.controller;

import com.eova.aop.AopContext;
import com.eova.aop.MetaObjectIntercept;
import com.eova.common.Easy;
import com.eova.model.*;
import com.eova.service.sm;
import com.eova.template.common.util.TemplateUtil;
import com.eova.vo.MenuConfig;
import com.eova.widget.WidgetManager;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.DbPro;
import com.jfinal.plugin.activerecord.Record;
import org.xnsg.app.controller.utils.ControllerHelper;
import org.xnsg.app.core.bean.Result;

import java.sql.Timestamp;
import java.util.*;

/**
 * Created by zhaopan on 2017/4/23.<br>
 *
 * @Description:
 */
public class AppGridController extends Controller {
    final Controller ctrl = this;
    protected MetaObjectIntercept intercept = null;
    private String errorInfo = "";
    private final Record record = new Record();

    public void list() {
        String menuCode = this.getPara(0);
        Menu menu = Menu.dao.findByCode(menuCode);
        MenuConfig config = menu.getConfig();
        String objectCode = config.getObjectCode();
        MetaObject object = MetaObject.dao.getByCode(objectCode);
        List fields = MetaField.dao.queryByObjectCode(objectCode);
        User user = (User) this.getSessionAttr("user");
        List btnList = Button.dao.queryByMenuCode(menuCode, user.getInt("rid").intValue());
        Map resultMap = new HashMap();
        //resultMap.put("isQuery", Boolean.valueOf(MetaObject.dao.isExistQuery(objectCode)));
        //resultMap.put("menu", menu);
        resultMap.put("btnList", btnList);
        //resultMap.put("object", object);
        resultMap.put("fields", fields);
        this.renderJson(new Result(resultMap));
    }

    public void detail() {
        String objectCode = this.getPara(0);
        String pkValue = this.getPara(1);
        String userId = getPara("userId");
        User user = User.dao.getByLoginId(getPara("userId"));
        this.setSessionAttr("user", user);
        MetaObject object = sm.meta.getMeta(objectCode);
        Record record = Db.use(object.getDs()).findById(object.getView(), object.getPk(), new Object[]{pkValue});

        MetaField ei;
        Object value;
        for (Iterator var7 = object.getFields().iterator(); var7.hasNext(); ei.put("value", value)) {
            ei = (MetaField) var7.next();
            String key = ei.getEn();
            value = record.get(key);
            if (value == null) {
                value = "";
            }
        }

        WidgetManager.buildRef(this, object);
        Map resultMap = new HashMap();
        //resultMap.put("object", object);
        //resultMap.put("fields", object.getFields());
        // this.buildWidget(resultMap);
        //状态
        List<Record> statuses= ControllerHelper.comboJson(null, "c_aj_wgxx", "status", new Object[]{user});
        Map<String, String> statusMap = new HashMap<String, String>();
        for (Record re : statuses)
        {
            statusMap.put(String.valueOf(re.get("id")), re.getStr("cn"));
        }

        //resultMap.put("status", ControllerHelper.comboJson(null, "c_aj_wgxx", "status", new Object[]{this.getSessionAttr("user")}));
        //社区(村)名称
        //resultMap.put("fid", ControllerHelper.findCnByEn("c_aj_wgxx", "fid", record.getStr("fid"), new Object[]{this.getSessionAttr("user")}));
        List<Record> fids= ControllerHelper.comboJson(null, "c_aj_wgxx", "fid", new Object[]{user});
        Map<String, String> fidMap = new HashMap<String, String>();
        for (Record re : fids)
        {
            fidMap.put(String.valueOf(re.get("id")), re.getStr("cn"));
        }
        for (MetaField field : object.getFields()){
            if ("fid".equals(field.getStr("en")))
            {
                resultMap.put(field.getStr("en"), fidMap.get(String.valueOf(field.get("value"))));
            }else if("status".equals(field.getStr("en"))){
                resultMap.put(field.getStr("en"), statusMap.get(String.valueOf(field.get("value"))));
            }else{
                resultMap.put(field.getStr("en"), String.valueOf(field.get("value")));
            }
        }

        this.renderJson(new Result(resultMap));
    }
    public void add() throws Exception {
        String objectCode = this.getPara(0);
        MetaObject object = sm.meta.getMeta(objectCode);
        Iterator var4 = object.getFields().iterator();

//        while(var4.hasNext()) {
//            MetaField ac = (MetaField)var4.next();
//            ac.put("is_disable", Boolean.valueOf(false));
//        }

        WidgetManager.buildRef(this, object);
        this.intercept = (MetaObjectIntercept) TemplateUtil.initIntercept(object.getBizIntercept());
        if(this.intercept != null) {
            AopContext ac1 = new AopContext(this.ctrl, object);
            this.intercept.addInit(ac1);
        }

        Map resultMap = new HashMap();
        //resultMap.put("object", object);
        resultMap.put("fields", object.getFields());
        resultMap.put("status", ControllerHelper.comboJson(null, "c_aj_wgxx", "status", new Object[]{this.getSessionAttr("user")}));
        this.removeSessionAttr("user");
        this.renderJson(new Result(resultMap));
    }
    public void update() throws Exception {
        User user = User.dao.getByLoginId(getPara("userId"));
        this.setSessionAttr("user", user);
        MetaObject object = this.buildFormData(true);
        this.intercept = (MetaObjectIntercept)TemplateUtil.initIntercept(object.getBizIntercept());
        if(this.intercept != null) {
            AopContext ac = new AopContext(this.ctrl, object);
            this.intercept.updateInit(ac);
        }
        Map resultMap = new HashMap();
        //resultMap.put("object", object);
        //resultMap.put("fields", object.getFields());
        for (MetaField field : object.getFields()){
            resultMap.put(field.getStr("en"), String.valueOf(field.get("value")));
            resultMap.put(field.getStr("en")+"_qx", (boolean)field.get("is_update"));

        }
        this.removeSessionAttr("user");

        this.renderJson(new Result(resultMap));
    }
    public MetaObject buildFormData(boolean isEdit) {
        String objectCode = this.getPara(0);
        String pkValue = this.getPara(1);
        MetaObject object = sm.meta.getMeta(objectCode);
        Record record = Db.use(object.getDs()).findById(object.getView(), object.getPk(), new Object[]{pkValue});

        MetaField ei;
        Object value;
        for(Iterator var7 = object.getFields().iterator(); var7.hasNext(); ei.put("value", value)) {
            ei = (MetaField)var7.next();
            String key = ei.getEn();
            value = record.get(key);
            if(value == null) {
                value = "";
            }

//            if(!isEdit) {
//                ei.set("is_disable", Boolean.valueOf(true));
//            }
        }

        //WidgetManager.buildRef(this, object);

        //this.buildWidget();
        return object;
    }
    //添加
    public void insertGridInfo() {
        String fid = getPara("fid"); // ID
        String aname = getPara("aname"); // 网格名称
        String address = getPara("address"); // 地址
        Double lat = Double.parseDouble(getPara("lat"));  // 纬
        Double lon = Double.parseDouble(getPara("lon")); // 经
        String person = getPara("person"); // 负责人
        String persontel = getPara("persontel"); // 联系电话
        String alevel = getPara("alevel", "6"); // 行政区划等级，6代码网格
        String istal = getPara("istal", "1"); // 不明白什么意思
        String status = getPara("status", "1"); // 状态
        String introduce = getPara("introduce");

        // 生成主键，根据选择的村的ID，找到目前最大的，然后加递增
        Record record = DbPro.use("eova").findFirst("select max(xid) latest from eova_xzqh where fid = ?", fid);
        Long latest = Long.parseLong(record.<String>get("latest", "0"));
        if (latest == 0) latest = Long.parseLong(fid + "001");
        else latest++;

        Record addRecord = new Record();
        addRecord.set("fid", fid);
        addRecord.set("aname", aname);
        addRecord.set("address", address);
        addRecord.set("lat", lat);
        addRecord.set("lon", lon);
        addRecord.set("person", person);
        addRecord.set("persontel", persontel);
        addRecord.set("alevel", alevel);
        addRecord.set("istail", istal);
        addRecord.set("status", status);
        addRecord.set("introduce", introduce);
        addRecord.set("xid", latest);
        addRecord.set("createtime", new Timestamp(System.currentTimeMillis()));

        List<Record> records = new ArrayList<>();
        records.add(addRecord);

        try {
            DbPro.use("eova").batchSave("eova_xzqh", records, 1);
            renderJson(new Easy());
        } catch (Exception e) {
            e.printStackTrace();
            renderJson(new Easy(e.getMessage(), false));
        }
    }

}
